<script setup lang="ts">
import { add, update, checkExist } from "@/api/system/user";
import { getRoleListSelect } from "@/api/system/role";
import { useForm } from "@/hooks/useForm";
import { watch, ref, computed, reactive, toRefs } from "vue";
import { isMainAccount, isMobile } from "@/utils/validate";
import { getDeptTree } from "@/api/system/dept";
import { getPostSelect } from "@/api/system/post";

//定义自定义事件
const emit = defineEmits(["refresh"]);

const initData = {
  accountNonExpired: true,
  accountNonLocked: true,
  credentialsNonExpired: true,
  userPostList: []
};

const {
  formRef,
  title,
  type,
  visible,
  loading,
  oldFormData,
  formData,
  open,
  close,
  submitForm,
} = useForm<SysUserType>({ add, update, initData }, emit);

defineExpose({
  open,
});

const disabled = computed(() => type.value === "edit");

const roleOptions = ref([]);
const deptOptions = ref([]);
const postOptions = ref([]);

watch(
  () => visible.value,
  (val) => {
    if (!val) return;
    loadRoleOptions();
    loadDeptOptions();
    loadPostOptions();
  }
);

async function loadRoleOptions() {
  try {
    loading.value = true;
    const { data } = await getRoleListSelect();
    if (data && data.length > 0) {
      roleOptions.value = data.map((item: any) => ({
        value: item.roleId,
        label: item.roleName,
      }));
    } else {
      roleOptions.value = [];
    }
  } catch (error) {
  } finally {
    loading.value = false;
  }
}

async function loadDeptOptions() {
  try {
    loading.value = true;
    const { data } = await getDeptTree();
    if (data && data.length > 0) {
      deptOptions.value = data;
    } else {
      deptOptions.value = [];
    }
  } catch (error) {
  } finally {
    loading.value = false;
  }
}

async function loadPostOptions() {
  try {
    loading.value = true;
    const { data } = await getPostSelect();
    if (data && data.length > 0) {
      postOptions.value = data.map((item: any) => ({
        value: item.postId,
        label: item.postName,
      }));
    } else {
      postOptions.value = [];
    }
  } catch (error) {
  } finally {
    loading.value = false;
  }
}

//校验用户账号是否存在
async function usernameValidator(rule: any, value: string, callback: Function) {
  if (!value || value == "") {
    return callback(new Error("用户账号为必填项！"));
  }
  if (!isMainAccount(value)) {
    return callback(new Error("用户账号必须为6~30位数字/字母/下划线！"));
  }
  if (oldFormData.value.userName !== value) {
    const { data } = await checkExist({ username: value });
    if (data) return callback(new Error("用户账号已被注册，请更换一个！"));
  }
  callback();
}

//校验手机号是否存在
async function mobileValidator(rule: any, value: string, callback: Function) {
  //可以为空，直接放行
  if (!value || value == "") {
    return callback();
  }
  if (!isMobile(value)) {
    return callback(new Error("手机号码格式不正确！"));
  }
  if (oldFormData.value.phonenumber !== value) {
    const { data } = await checkExist({ mobile: value });
    if (data) return callback(new Error("手机号码已存在，请更换一个！"));
  }
  callback();
}

interface DomainItem {
  deptId: string;
  postId: string;
}

const addDomain = () => {
  formData.value.userPostList.push({
    deptId: "",
    postId: "",
  });
};

const removeDomain = (item: DomainItem) => {
  const index = formData.value.userPostList.indexOf(item);
  if (index !== -1) {
    formData.value.userPostList.splice(index, 1);
  }
};
</script>

<template>
  <el-drawer
    :title="title + '用户'"
    v-model="visible"
    :before-close="close"
    direction="rtl"
    size="650px"
  >
    <el-form
      v-loading="loading"
      ref="formRef"
      :model="formData"
      label-width="85px"
      label-position="right"
      status-icon
      label-suffix=":"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item
            label="用户昵称"
            prop="nickName"
            :rules="{
              required: true,
              message: '用户昵称为必填项！',
              trigger: 'blur',
            }"
          >
            <el-input
              v-model="formData.nickName"
              placeholder="请输入用户昵称"
              maxlength="30"
              show-word-limit
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="用户账号"
            prop="userName"
            :rules="{
              required: true,
              validator: usernameValidator,
              trigger: 'blur',
            }"
          >
            <el-input
              v-model.trim="formData.userName"
              placeholder="请输入用户账号"
              maxlength="30"
              show-word-limit
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="手机号码"
            prop="phonenumber"
            :rules="{ validator: mobileValidator, trigger: 'blur' }"
          >
            <el-input
              v-model.trim="formData.phonenumber"
              placeholder="请输入手机号码"
              maxlength="20"
              show-word-limit
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            v-if="title == '新增'"
            label="登录密码"
            prop="password"
            :rules="{
              required: true,
              pattern: /^[a-zA-Z0-9]{6,30}$/,
              message: '密码必须是6~30位数字/字母/下划线！',
              trigger: 'blur',
            }"
          >
            <el-input
              v-model.trim="formData.password"
              placeholder="请输入6~30位登录密码"
              type="password"
              :disabled="disabled"
              maxlength="30"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item v-else label="登录密码" prop="password">
            <el-input
              v-model.trim="formData.password"
              placeholder="请输入6~30位登录密码"
              type="password"
              :disabled="disabled"
              maxlength="30"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="电子邮箱" prop="email">
            <el-input
              v-model.trim="formData.email"
              placeholder="请输入电子邮箱"
              maxlength="30"
              show-word-limit
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="分配角色" prop="roleIds">
            <el-select-v2
              multiple
              v-model="formData.roleIds"
              :options="roleOptions"
              placeholder="请选择分配给用户的角色"
              style="width: 100%"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="选择部门"
            prop="deptId"
            :rules="{
              required: true,
              message: '部门为必填项！',
              trigger: 'blur',
            }"
          >
            <el-cascader
              v-model="formData.deptId"
              :options="deptOptions"
              :props="{
                checkStrictly: true,
                emitPath: false,
                value: 'id',
                label: 'label',
              }"
              placeholder="请选择分配给用户的部门"
              clearable
              class="w100"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="选择岗位"
            prop="postId"
          >
            <el-select-v2
              v-model="formData.postId"
              :options="postOptions"
              placeholder="请选择分配给用户的岗位"
              style="width: 100%"
              clearable
            />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
                    <el-form-item label="账号锁定" prop="accountNonLocked" :rules="{required: true,message:'账号锁定为必填项！',trigger:'change'}">
                        <el-radio-group v-model="formData.accountNonLocked">
                            <el-radio :value="true" border>未锁定</el-radio>
                            <el-radio :value="false" border>已锁定</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="账号过期" prop="accountNonExpired" :rules="{required: true,message:'账号过期为必填项！',trigger:'change'}">
                        <el-radio-group v-model="formData.accountNonExpired">
                            <el-radio :value="true" border>未过期</el-radio>
                            <el-radio :value="false" border>已过期</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="密码过期" prop="credentialsNonExpired" :rules="{required: true,message:'密码过期为必填项！',trigger:'change'}">
                        <el-radio-group v-model="formData.credentialsNonExpired">
                            <el-radio :value="true" border>未过期</el-radio>
                            <el-radio :value="false" border>已过期</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col> -->
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="formData.remark"
              type="textarea"
              placeholder="请输入备注信息"
              maxlength="100"
              show-word-limit
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-button @click="addDomain">新增任职</el-button>
        </el-col>
        <el-col
          :span="24"
          v-for="(domain, index) in formData.userPostList"
          :key="index"
        >
          <el-row :gutter="10">
            <el-col :span="10">
              <el-form-item
                label="部门"
                :prop="'userPostList.' + index + '.deptId'"
                :rules="{
                  required: true,
                  message: '请选择分配给用户的部门',
                  trigger: 'blur',
                }"
              >
                <el-cascader
                  v-model="domain.deptId"
                  :options="deptOptions"
                  :props="{
                    checkStrictly: true,
                    emitPath: false,
                    value: 'id',
                    label: 'label',
                  }"
                  placeholder="请选择分配给用户的部门"
                  clearable
                  class="w100"
                />

              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item
                label="岗位"
                :prop="'userPostList.' + index + '.postId'"
              >
                <el-select-v2
                  v-model="domain.postId"
                  :options="postOptions"
                  placeholder="请选择分配给用户的岗位"
                  style="width: 100%"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="4">
                <el-button class="mt-2" @click.prevent="removeDomain(domain)">
                  删除
                </el-button>
            </el-col>
          </el-row>
        </el-col>
        <el-form-item>
           <!-- <el-button type="primary" @click="submitForm(formRef)">Submit</el-button> -->

          <!-- <el-button @click="resetForm(formRef)">Reset</el-button>  -->
        </el-form-item>
      </el-row>
    </el-form>
    <template #footer>
      <el-row justify="center" class="mt10">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </el-row>
    </template>
  </el-drawer>
</template>

<style scoped>
</style>
